﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using Microsoft.Win32;
using System.ComponentModel;
using System.Reflection;
using Newtonsoft.Json;


namespace GSLMS.Core
{
    public class Helper
    {

        /// <summary>
        /// 缩略图宽度
        /// </summary>
        public static readonly int PhotoWidth = 200;
        /// <summary>
        /// 缩略图高度
        /// </summary>
        public static readonly int PhotoHeight = 200;

        /// <summary>
        /// 指定 缩略图裁剪模式 CUT（指定宽高）,W（指定宽度，高自动）,H(指定高度，宽自动)
        /// </summary>
        public static readonly string PhotoCutMode = "CUT";

        /// <summary>
        /// 指定列表页 每页显示条数
        /// </summary>
        public static readonly int PageSize = 3;

        public static string MD5(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            //MD5 md5 = new MD5CryptoServiceProvider();
            //byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
            //return System.Text.Encoding.Default.GetString(result);

        }

        public static string GetGuid
        {
            get { return Guid.NewGuid().ToString("N"); }

        }

        public const string DATETIME = "yyyy-MM-dd";

        public static string FormatDate(object dateTime)
        {
            if (dateTime == null) return string.Empty; ;
            DateTime _datetime = DateTime.Now;
            DateTime.TryParse(dateTime.ToString(), out _datetime);
            return _datetime.ToString(DATETIME);
        }

        public const string DEFAULTPWD = "88888888";

        public static List<string> SuperUsers
        {
            get
            {
                List<string> superUsers = new List<string>();
                superUsers.Add("luochengbang");
                superUsers.Add("admin");
                superUsers.Add("administrator");
                superUsers.Add("root");
                superUsers.Add("super");
                return superUsers;
            }
        }

        public static T Clone<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }

        // 通过系统中的Content Type来获取MIME TYPE
        public static string GetMimeType(string fileName)
        {
            string mimeType = "application/unknown";
            string ext = Path.GetExtension(fileName).ToLower();
            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(ext);
            if (regKey != null && regKey.GetValue("Content Type") != null)
            {
                mimeType = regKey.GetValue("Content Type").ToString();
            }
            return mimeType;
        }

        /// <summary>
        ///  string to decimal
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static decimal ToDecimal(string str)
        {
            decimal dec = 0;
            try
            {
                dec = Convert.ToDecimal(str.Trim());
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            return dec;
        }

        /// <summary>
        ///  string to decimal
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static decimal ToDecimal(object str)
        {
            decimal dec = 0;
            try
            {
                dec = Convert.ToDecimal(str.ToString().Trim());
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            return dec;
        }

        /// <summary>
        /// string To long(Int64)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static long ToLong(string str)
        {
            long num = 0;

            try
            {
                num = Convert.ToInt64(str.Trim());
            }
            catch (Exception ex)
            {
                ex.ToString();
            }


            return num;
        }

        /// <summary>
        /// string to int
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int ToInt(string str)
        {
            int num = 0;
            try
            {
                num = Convert.ToInt32(str.Trim());
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            return num;
        }

        /// <summary>
        /// 转换Int32
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns></returns>
        public static int ToInt(string str, int defValue)
        {
            bool flag = false;
            int outInt = defValue;
            if (str != null && str.Trim() != "")
            {
                flag = Int32.TryParse(str, out outInt);
                if (flag)
                    return outInt;
                else
                    return defValue;
            }

            return outInt;
        }

        /// <summary>
        /// 转换成decimal
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns></returns>
        public static decimal ToDecimal(string str, decimal defValue)
        {
            bool flag = false;
            decimal outDecimal = defValue;
            if (str != null && str.Trim() != "")
            {
                flag = decimal.TryParse(str, out outDecimal);
                if (flag)
                    return outDecimal;
                else
                    return defValue;
            }

            return outDecimal;
        }

        /// <summary>
        /// 转换成decimal
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <param name="decimals">精度</param>
        /// <returns></returns>
        public static decimal ToDecimal(string str, decimal defValue, int decimals)
        {
            bool flag = false;
            decimal outDecimal = defValue;
            if (str != null && str.Trim() != "")
            {

                flag = decimal.TryParse(str, out outDecimal);
                outDecimal = Decimal.Round(outDecimal, decimals);
                if (flag)
                    return outDecimal;
                else
                    return defValue;
            }

            return outDecimal;
        }


        /// <summary>
        /// 转换成decimal
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <param name="decimals">精度</param>
        /// <returns></returns>
        public static decimal ToDecimal(object str, decimal defValue, int decimals)
        {
            bool flag = false;
            decimal outDecimal = defValue;
            if (str != null && str.ToString().Trim() != "")
            {

                flag = decimal.TryParse(str.ToString(), out outDecimal);
                outDecimal = Decimal.Round(outDecimal, decimals);
                if (flag)
                    return outDecimal;
                else
                    return defValue;
            }

            return outDecimal;
        }

        public static T ConvertObject2<T>(object obj) where T : class,new()
        {
            T t = new T();
            if (obj == null) return t;
            Type type = typeof(T);
            Type underlyingType = Nullable.GetUnderlyingType(type);
            if (type.IsAssignableFrom(obj.GetType())) // 如果待转换对象的类型与目标类型兼容，则无需转换
            {
                return obj as T;
            }
            else if ((underlyingType ?? type).IsEnum) // 如果待转换的对象的基类型为枚举
            {
                if (underlyingType != null && string.IsNullOrEmpty(obj.ToString())) // 如果目标类型为可空枚举，并且待转换对象为null 则直接返回null值
                {
                    return null;
                }
                else
                {
                    return Enum.Parse(underlyingType ?? type, obj.ToString()) as T;
                }
            }
            else if (typeof(IConvertible).IsAssignableFrom(underlyingType ?? type)) // 如果目标类型的基类型实现了IConvertible，则直接转换
            {
                try
                {
                    return Convert.ChangeType(obj, underlyingType ?? type, null) as T;
                }
                catch
                {
                    return (underlyingType == null ? Activator.CreateInstance(type) : null) as T;
                }
            }
            else
            {
                TypeConverter converter = TypeDescriptor.GetConverter(type);
                if (converter.CanConvertFrom(obj.GetType()))
                {
                    return converter.ConvertFrom(obj) as T;
                }
                ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                if (constructor != null)
                {
                    object o = constructor.Invoke(null);
                    PropertyInfo[] propertys = type.GetProperties();
                    Type oldType = obj.GetType();
                    foreach (PropertyInfo property in propertys)
                    {
                        PropertyInfo p = oldType.GetProperty(property.Name);
                        if (property.CanWrite && p != null && p.CanRead)
                        {
                            property.SetValue(o, p.GetValue(obj, null), null);
                        }
                    }
                    return o as T;
                }
            }
            return obj as T;
        }

        public static T ConvertObject<T>(object obj) where T : class,new()
        {
            T t = new T();
            t = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj));
            return t;
        }
    }
}
